Scroll Progress Bar

Bubble sort

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Here's how it can implement bubble sort in C++:

Program:

#include <iostream>

void bubbleSort(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap arr[j] and arr[j + 1]
                std::swap(arr[j], arr[j + 1]);
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Original array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    bubbleSort(arr, size);

    std::cout << "\nSorted array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}
In this code:
  • bubbleSort is a function that takes an array arr and its size size as parameters and sorts the array in ascending order using the bubble sort algorithm.
  • The outer loop (with index i) iterates through the array from the beginning to the second-to-last element.
  • In each iteration of the outer loop, the inner loop (with index j) iterates through the unsorted portion of the array (from the beginning to size - i - 1).
  • If the element at arr[j] is greater than the element at arr[j + 1], a swap is performed to put them in the correct order.
  • The bubble sort algorithm continues until no more swaps are needed.

When run this code, it will sort the arr array in ascending order using bubble sort and print both the original and sorted arrays. Here's a Sample Output:

Program:

Original array: 64 34 25 12 22 11 90 
Sorted array: 11 12 22 25 34 64 90 

As it can see, the array is sorted in ascending order after applying the bubble sort algorithm.


question


answer

question2


answer2